// 在全局添加时间控制配置
interface TimingConfig {
    baseDelay: number;        // 基础延迟时间
    randomRange: number;      // 随机延迟范围
    speedFactor: number;      // 动态速度因子
    fatigueThreshold: number; // 疲劳操作阈值
  }
  
  const timing: TimingConfig = {
    baseDelay: 3000,          // 3秒基础延迟
    randomRange: 7000,        // 0-7秒随机延迟
    speedFactor: 1.0,         // 初始速度因子
    fatigueThreshold: 10      // 连续10次操作后触发疲劳模式
  };

  interface ApiResponse<T = any> {
    code: number;
    msg?: string;
    data?: T;
  }
const buttonId = 'scrapeButton';

function createButton() {
  // Check if button already exists to avoid duplicates
  if (document.getElementById(buttonId)) return;

  const button = document.createElement('button');
  button.id = buttonId;
  button.textContent = '此页面支持采集到爆蚁ERP【开始采集】';
  
  button.style.position = 'fixed';
  button.style.bottom = '100px';
  button.style.left= '40%';
  button.style.zIndex = '1000000';
  button.style.backgroundColor = '#0064fa';
  button.style.color = '#FFF';
  button.style.border = 'none';
  button.style.borderRadius = '10px';
  button.style.padding = '10px';
  button.style.cursor = 'pointer';
  button.style.fontSize = '16px';
  document.body.appendChild(button);

  button.addEventListener('click', () => {
    checkLoginAndStartScraping();
  
  });
}

  
  // 智能延迟函数
  function intelligentDelay(pageCount: number): Promise<void> {
    return new Promise(resolve => {
      // 动态调整系数（根据操作次数自动降速）
      const dynamicFactor = Math.max(0.5, 1 - pageCount * 0.03);
      
      // 疲劳模式检测
      const fatigueMultiplier = pageCount > timing.fatigueThreshold ? 1.5 : 1;
  
      // 计算最终延迟时间
      const delay = (
        timing.baseDelay * dynamicFactor * fatigueMultiplier + 
        Math.random() * timing.randomRange
      );
  
      console.log(`本次延迟: ${Math.round(delay)}ms`);

      setTimeout(resolve, delay);
    });
  }

// 页面加载完成后创建按钮
document.addEventListener('DOMContentLoaded', createButton);

// 使用 MutationObserver 监听动态内容的变化
const observer = new MutationObserver(() => {
  createButton(); // Continuously check and create the button if needed

});

// Start observing document.documentElement for changes
observer.observe(document.documentElement, { childList: true, subtree: true });


interface CrawlResult {
    html?: string;
    list?: string[];
    next?: string;
    error?: string;  // 新增错误字段
}

interface HtmlResponse {
    code: number;
    data: string[];
}


function crawl(url: string, callback: (result: CrawlResult) => void, retries: number = 3, filterCustomsGoods: boolean = false): void {
    const headers = {
        'User-Agent': getRandomUserAgent(),
        'Accept-Language': Math.random() > 0.5 ? 'en-US,en;q=0.9' : 'en-GB,en;q=0.8'
      };
    
   
    chrome.runtime.sendMessage({ action: 'scrape', url:url,headers: headers, }, (response: { data: string }) => {
      
      
        
        let $html: JQuery<HTMLElement> | undefined;
        let nextPageUrl: string | undefined;
        let result: CrawlResult = { html: response.data};

        let pageType = 0;
        let amazonDomain = ""; // 用于存储动态解析的亚马逊站点域名
        // 动态解析亚马逊站点域名
        const urlParts = new URL(url);
        if (urlParts.hostname.includes("amazon.")) {
            amazonDomain = `https://${urlParts.hostname}`;
        } else {
            console.error("Invalid Amazon URL");
        }
        if (url.includes("/s?")) {
            pageType = 1;
        } else if (url.includes("/stores/page/")) {
            pageType = 2;
        }
        else if(url.includes("/dp/") || url.includes("/gp/")){
            pageType = 3;
        }

     //   console.log("页面html"+result.html)
        if (result.html) {
            result.list = [];
            result.next = "";
         
  

            if (pageType === 1) {
               
                
                $html = $("<div></div>").html(result.html);
                const listItems = $html.find('[role="listitem"]').add($html.find("div.s-result-item"));

                result.list = Array.from(listItems).reduce((list: any, item) => {
                  const asin = item.getAttribute("data-asin");
                  const itemDetailElement = item.querySelector(
                    ".s-product-image-container a"
                  ) as HTMLAnchorElement;
                  const detailUrl = itemDetailElement?.href || "";
                  
                  const deliveryRecipeElement = item.querySelector('[data-cy="delivery-recipe"].a-section');
                  
                  let hasDeliveryImage = false;
                  if (deliveryRecipeElement) {
                    const deliveryImage = deliveryRecipeElement.querySelector('img.s-image');
                    hasDeliveryImage = !!deliveryImage;
                  }
                  
                  // 根据filterCustomsGoods参数决定是否过滤需要报关的商品
                  // 如果filterCustomsGoods为true，只添加不需要报关的商品（!hasDeliveryImage）
                  // 如果filterCustomsGoods为false，添加所有商品
                  const shouldAdd = filterCustomsGoods ? !hasDeliveryImage : true;
                  
                  if (asin && detailUrl && shouldAdd) {
                    list.push(detailUrl);
                  }
                  return list;
                }, []);

                nextPageUrl = $html.find("span.pagnRA a.pagnNext").attr("href")
                    || $html.find("#pagnNextLink").attr("href")
                    || $html.find(".a-text-center li.a-last a").attr("href")
                    || ($html.find("span.s-pagination-strip a").last().first().attr("href") || "");

                result.next = nextPageUrl && !$html.find('div[role="navigation"]').find("span.s-pagination-next.s-pagination-disabled").length
                    ? `${amazonDomain}${nextPageUrl}`
                    : "";

                $html.remove();
            } else if (pageType === 2) {
                
                return; // Ensure we don't call `callback(result)` twice.
            }
            else if (pageType === 3) {

              result.list = [window.location.href];
              result.next = ""; // 详情页没有下一页
            }

            callback(result);
        } else {
            result.html = "";
            callback(result);
        }
    });
}

function getRandomUserAgent() {
    const agents = [
// Windows最新Chrome
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
// macOS最新Safari
'Mozilla/5.0 (Macintosh; Intel Mac OS X 13_4_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15',
// iPhone最新iOS
'Mozilla/5.0 (iPhone14,6; CPU iPhone OS 16_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Mobile/15E148 Safari/604.1',
// 微信内置浏览器
'Mozilla/5.0 (Linux; Android 14; M2012K11AG Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/116.0.0.0 Mobile Safari/537.36 MMWEBID/9538 MicroMessenger/8.0.44.2500(0x28002C51) WeChat/arm64',
 // iPad Pro
 'Mozilla/5.0 (iPad; CPU OS 16_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Mobile/15E148 Safari/604.1',
// 华为鸿蒙手机
'Mozilla/5.0 (Linux; HarmonyOS; LIO-AN00m; HMSCore 6.13.0.302) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Mobile Safari/537.36',
// 桌面版Opera
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 OPR/107.0.0.0',

    ];
    return agents[Math.floor(Math.random() * agents.length)];
  }
  function getRandomDelay(min: number, max: number) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  function sendMessage<T>(message: any): Promise<T> {
    return new Promise(resolve => {
      chrome.runtime.sendMessage(message, resolve);
    });
  }

async function sendToBackend(data: { sourceUrl:string,urls: string[] }) {
  
    const storage = await chrome.storage.sync.get([
        'baoyiplus_accessToken',
        'baoyiplus_expiresIn',
        'baoyiplus_username'
      ]);
      const { 
        baoyiplus_accessToken = '', 
        baoyiplus_expiresIn = 0,
        baoyiplus_username = ''
      } = storage;
    
    let btn=$('#scrapeButton');
    
   
    try {
        const response = await sendMessage<ApiResponse>({
            type: 'callApi',
            data: data,
            token:baoyiplus_accessToken,
          });
      

          console.log('采集API响应:', response);
      
        
       // console.log('后台返回结果:', result);
       if (response?.code === 0) {
        btn.text('采集完成,本次总采集('+totalItems.length+')个商品,具体请进入爆蚁ERP系统查看,如需重新采集请刷新页面');
        btn.prop('disabled', true);

        }
        else{
            btn.text(response.msg||'')
        }
        btn.prop('disabled', false);
    } catch (error) {
        console.error('Error sending data to backend:', error);
    }

// 内容脚本中调用

    
}
let totalItems: string[] = [];

async function autoScrape(url: string,pageCount: number = 0,maxPages: number = 5, filterCustomsGoods: boolean = false): Promise<void>  {
    // 最多获取的页数

    let btn=$('#scrapeButton');
   // 初始化页数计数器

   try {
     

    // 前置延迟
    await intelligentDelay(pageCount);
 // 翻页前随机交互
 //await simulateHumanInteraction();
    crawl(url, async (result: CrawlResult) => {
       if (result.error) {
        btn.text(`采集失败: ${result.error}`);
        return;
      }
    
        if (result.list && result.list.length > 0) {
            totalItems= totalItems.concat(result.list);
            btn.text('采集中>>>,数量('+totalItems.length+'),当前第'+pageCount+'页,(卡住在1分钟内属于正常，超过请切换网络环境)')
            //console.log('Found product URLs:', result.list); //第1页面
            
        }
       
      
        if (result.next && pageCount <maxPages) {
            // Continue to the next page
            autoScrape(result.next,pageCount+1,maxPages,filterCustomsGoods); // 继续下一页
        } else {
            //const dataToSend = { urls: totalItems };
            let userkey:   string[] | null = null;
            const storage = await chrome.storage.sync.get([
                'baoyiplus_accessToken',
                'baoyiplus_expiresIn',
                'baoyiplus_username'
              ]);
                // 解构赋值，设置默认值防止undefined
            const { 
              baoyiplus_accessToken = '', 
              baoyiplus_expiresIn = 0,
              baoyiplus_username = ''
            } = storage;
          
         
                if (baoyiplus_accessToken ) {
                    const isExpired = checkTokenExpired(baoyiplus_expiresIn);
                    if (!isExpired) {
                    const dataToSend = {sourceUrl:url, urls: totalItems };
                    // 确保在获取 userkey 后再调用 sendToBackend
                    sendToBackend(dataToSend);
                    }
                    else {
                        alert('登录已经过期，请先点击右上角重新登录');
                        //userkey = null;
                    }
                } 
                else{
                    alert('还未登录,请先点击右上角登录'); 
                }
            
        
           
            
            
           
        }
    }, 3, filterCustomsGoods); } catch (error) {
        console.error('异常:', error);
        btn.text('操作被中断，请检查');
      }
    
}


  // 检查token是否过期（针对时间戳格式）
  function checkTokenExpired(expiresIn: string | number): boolean {
    if (!expiresIn) return true;
    
    // 统一转换为数字
    const expiryTime = typeof expiresIn === 'string' 
      ? parseInt(expiresIn) 
      : expiresIn;
    
    // 获取当前时间戳（毫秒）
    const currentTime = new Date().getTime();
    return currentTime > expiryTime;
  }
// 新增人类交互模拟
async function simulateHumanInteraction(): Promise<void> {
    return new Promise(resolve => {
      // 随机滚动
      window.scrollBy({
        top: Math.random() * 500 - 250,
        behavior: 'smooth'
      });
  
     // 随机点击
    //const clickElement = document.body; // 或者选择一个特定的元素
    //clickElement.click();
    });
  }
  
  function simulateMouseMoves(remaining: number, callback: () => void): void {
    if (remaining <= 0) {
      callback();
      return;
    }
}

function getInputValues(): Promise<{
  page: number;
  filterCustomsGoods: boolean;
} | null> {
  // 创建对话框容器
  const dialog = document.createElement("div");
  dialog.style.position = "fixed";
  dialog.style.top = "50%";
  dialog.style.left = "50%";
  dialog.style.transform = "translate(-50%, -50%)";
  dialog.style.backgroundColor = "white";
  dialog.style.padding = "20px";
  dialog.style.borderRadius = "8px";
  dialog.style.boxShadow = "0 0 10px rgba(0,0,0,0.2)";
  dialog.style.zIndex = "9999";

  dialog.innerHTML = `
    <h3 style="margin-top: 0;">采集设置</h3>
    <div style="margin-bottom: 15px;">
      <label for="maxPagesInput" style="display: block; margin-bottom: 5px; font-weight: bold;">采集页数：</label>
      <input type="number" id="maxPagesInput" step="1" min="1" value="5" 
             style="width: 100%; padding: 8px; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px;">
    </div>
    <div style="margin-bottom: 15px;">
      <label style="display: block; margin-bottom: 5px; font-weight: bold;">报关商品过滤：</label>
      <div style="display: flex; align-items: center; gap: 10px;">
        <input type="radio" id="filterYes" name="filterCustoms" value="true">
        <label for="filterYes">过滤掉需要报关的商品</label>
      </div>
      <div style="display: flex; align-items: center; gap: 10px;">
        <input type="radio" id="filterNo" name="filterCustoms" value="false" checked>
        <label for="filterNo">不过滤，采集所有商品</label>
      </div>
    </div>
    <div style="display: flex; justify-content: space-between;">
      <button id="cancelBtn" style="padding: 8px 16px; background-color: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer;">取消</button>
      <button id="confirmBtn" style="padding: 8px 16px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">确认</button>
    </div>
  `;

  // 添加到body
  document.body.appendChild(dialog);

  const maxPagesInput = document.getElementById(
    "maxPagesInput"
  ) as HTMLInputElement;

  // 返回Promise
  return new Promise((resolve, reject) => {
    // 确认按钮点击事件
    document.getElementById("confirmBtn")?.addEventListener("click", () => {
      const page = parseInt(maxPagesInput.value);
      const filterCustomsGoods = (document.getElementById("filterYes") as HTMLInputElement)?.checked || false;

      // 验证输入
      if (isNaN(page)) {
        alert("请输入有效的页数！");
        reject();
        return;
      }

      if (page <= 0) {
        alert("页数必须大于0！");
        reject();
        return;
      }

      // 移除对话框
      document.body.removeChild(dialog);

      // 返回结果
      resolve({ page, filterCustomsGoods });
    });

    // 取消按钮点击事件
    document.getElementById("cancelBtn")?.addEventListener("click", () => {
      document.body.removeChild(dialog);
      resolve(null);
    });
  });
}

// Function to check login status and start scraping
async function checkLoginAndStartScraping() {
    const storage = await chrome.storage.sync.get([
        'baoyiplus_accessToken',
        'baoyiplus_expiresIn',
        'baoyiplus_username'
      ]);
        // 解构赋值，设置默认值防止undefined
    const { 
      baoyiplus_accessToken = '', 
      baoyiplus_expiresIn = 0,
      baoyiplus_username = ''
    } = storage;



//console.log("key"+key)
        if(baoyiplus_accessToken){
            const isExpired = checkTokenExpired(baoyiplus_expiresIn);
            if (!isExpired) {
           
            

            const currentUrl = window.location.href;
            
            // 使用新的对话框获取用户输入
            const inputValues = await getInputValues();
            if (!inputValues) {
                alert("采集已取消");
                return;
            }
            
            const { page: maxPages, filterCustomsGoods } = inputValues;
  
              // 调用autoScrape函数，并传递用户输入的页数
            
             // autoScrape(currentUrl,1);
              let btn=$('#scrapeButton')
              btn.text('采集准备中,马上开始>>>,如果一直未开始或者卡住超2分钟请切换本地网络环境')
              btn.prop('disabled', true); 
              autoScrape(currentUrl, 1, maxPages, filterCustomsGoods); // 第四个参数为是否过滤报关商品
            }
            else {
                alert('登录已经过期，请先点击右上角重新登录');
                //userkey = null;
            }
        }
        else {
            alert('还未登录，请先点击右上角插件进行登录');
        }
  
   

   // chrome.runtime.sendMessage({ action: "getCookies" }, function(response) {
   

   
}


